import React, { useState, useEffect } from "react";
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,Select,Divider,DatePicker,Tag} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'
import { Cascader,Tooltip} from 'antd';
import {findSubject} from 'api/index'
import classNames from "classnames";
import PreviewSubject from "components/LlxPreview/subject";
import QuoteSubject from "components/LlxPreview/QuoteSubject";


const { RangePicker } = DatePicker;
const { SHOW_CHILD } = Cascader;


const getValue = (value) => {
  switch (value) {
    case 1:
      return '听音选文'
    case 2:
      return '听音选图'
    case 3:
      return '看文选文'
    case 4:
      return '看文选图'
    case 5:
      return '看图选文'
    case 6:
      return '看图跟读'
    case 7:
      return '看文跟读'
    case 8:
      return '听音跟读'
    case 9:
      return '看文选音'
    case 10:
      return '听音选音'
    default:
      return
  }
}
const getTypeValue = (value) => {
  switch (value) {
    case 1:
      return '单选题'
    case 2:
      return '判断题'
    case 3:
      return '组合题'
    case 4:
      return '排序题'
    case 5:
      return '连线题'
    case 6:
      return '识读题'
    case 7:
      return '看图拼词'
    default:
        return
  }
}


function SubjectLibrary(props) {
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [expand,setExpand] = useState(true) //表单伸缩
const [total,setTotal] = useState(0) //总数量
const [form] = Form.useForm();//搜索列表
const [isModalVisiblePreview,setIsModalVisiblePreview] = useState(false)
const [id,setId] = useState('')
const [quoteData,setQuoteData] = useState({})
const [isModalVisibleQuo,setIsModalVisibleQuo] = useState(false)
// 表单数据
const formItem = [
  {label: '考点',type:'input', name: 'examination', span: 4 },
  {label: '考点种类', name: 'examinationTypeId' , span: 5 ,render: () => {
    return <Cascader  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'dictValue'}} options={dictionaries.SubjectType} multiple placeholder="请选择种类" />
}},
  {label: '题型', name: 'type', span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择题型'}
    options={dictionaries.QuestionType}
  >
  </Select>
}},
{label: '题目形式', name: 'subjectType', span: 5 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="dictValue"
  showSearch
  fieldNames={{value:'id',label:'dictValue'}}
  placeholder={'请选择题目形式'}
  options={dictionaries.QuestionCategory}
>
</Select>
}},
  {label: '来源', name: 'globalOriginType' , span: 5,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择来源'}
    options={dictionaries.SourceOption}
  >
  </Select>
} },
  {label: '创建人', name: 'createBy',  span: 4 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择创建人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新人', name: 'updateBy',  span: 5 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="userName"
    showSearch
    fieldNames={{value:'userName',label:'userName'}}
    placeholder={'请选择更新人'}
    options={dictionaries.UserSpecies}
  >
  </Select>
}},
  {label: '更新时间', name: 'updateTime', span: 5 ,render: () => {
    return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}}
]
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = [
      {title: '种类 + 考点',width:210, dataIndex: 'examination', key: 'examination', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap">
         {
           record.examinationName?.map((i,j)=>{
             return <p key={i.examinationTypedName}>{j+1}.{i.examinationTypedName} + {i.examination}</p>
           })
         }
       </div>
     }},
      {title: '题型', dataIndex: 'type', key: 'type', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap">
          {getTypeValue(text)}
       </div>
     }},
      {title: '来源', dataIndex: 'globalOriginTypeName', key: 'globalOriginTypeName', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap text-link" onClick={()=>goOtherPage(record)}>
          {text}
       </div>
     }},
      {title: '题目形式', dataIndex: 'subjectType', key: 'subjectType', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap">
          {getValue(text)}
       </div>
     }},
      {title: '标签', dataIndex: 'labels', key: 'labels',width:180, align: 'center', render: (text, record) => {
        return <div className="operate_link_group text-nowrap">
         {record.labels?.map((i,j)=>{
           return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
            {
              j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
            }
             </Tooltip>
         })}
       </div>
     }},
      {title: '创建人', dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
     }},
      {title: '负责人', dataIndex: 'manager', key: 'manager', align: 'center', render: (text, record) => {
        return <div className={classNames((props.userInfo.user.userName===record.qmanager)||(props.userInfo.user.userName===record.rmanager)?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {record.qmanager||record.rmanager}
       </div>
     }},
      {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
     }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:150},
      {title: '操作', dataIndex: 'active', key: 'active', align: 'center',width:100,render:(text, record) => {
        return  <>
         <span className="text-link" onClick={()=>previewSubject(record)}>预览</span>&nbsp;&nbsp;&nbsp;
         <span className="text-link" onClick={()=>lookImport(record)}>引用</span>
        </>
      }}
]

// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='test/subjectLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='test/subjectLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{
  setLoading(true)
  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }
    props.setPageDataFn('test/subjectLibrary',data) 

    const initialData = async () => {
      const {
        createBy,
        endTime,
        subjectType,
        manager,
        examination,
        startTime,
        updateBy,
        examinationTypeId,
        type,
        globalOriginType
      } = form.getFieldValue()

      const params = {
        currPage:value&&value.pageSize?value.current:pagination.current,
        pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
        createBy,
        endTime,
        subjectType,
        manager,
        examination,
        startTime,
        updateBy,
        examinationTypeId:examinationTypeId?.map(i=>i[i.length-1]),
        type,
        globalOriginType,
        globalType:4
      }
     
        const res = await findSubject(params)
        const data = res.result.records || []
        data.forEach((i,y)=>{
          i.sort =value&&value.pageSize?value.pageSize * (value.current - 1) + y + 1:pagination.pageSize * (pagination.current - 1) + y + 1
        })
        
        setDataSource(data)
        setTotal(res.result.total)
        setLoading(false)
    }
    initialData()
    }
 // 2.重置表单
 const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:20
  })
   getNewList()
 }
//  3.预览题目
const previewSubject = (value) =>{
  setId(value.id)
  setIsModalVisiblePreview(true)
}
// 4.预览引用
const lookImport = (value) => {
  setQuoteData(value.referenceList)
  setIsModalVisibleQuo(true)
}
// 5.前往别的页
const goOtherPage = (value) => {
  switch(value.globalOriginTypeName) {
    case '主题课':
      props.history.push('/view/plan/themeSubjectInfo?id=' + value.id)
      props.addRouter({
        menuName:'主题课详情',url:'plan/themeSubjectInfo?id=' + value.id 
      })
    break
    case '精读书':
      props.history.push('/view/book/intensiveBookInfo?id=' + value.id)
      props.addRouter({
        menuName:'精读书详情',url:'book/intensiveBookInfo?id=' + value.id 
      })
    break
    case '试卷':
      props.history.push('/view/test/testPaperInfo?id=' + value.id)
      props.addRouter({
        menuName:'试卷详情',url:'test/testPaperInfo?id=' + value.id 
      })
    break
    default:
      return
  }
}
// 7.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}



return <div className="app-content animate__animated animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={expand?formItem:formItem.filter((i,j)=>j<5)}/>

       {/* 操作按钮 */}
       <div className="operate-btn">
         <div></div>
       <div>
         <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
          <Button  type='link' onClick={()=>setExpand(i=>!i)} className='animate__animated animate__fadeInRight'>{expand?'收起':'展开'}</Button>
       </div>
    </div>

    <Divider />

    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={false}
     height={!expand?320:380}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

   {/* 预览题目 */}
   <PreviewSubject  id={id} isModalVisible={isModalVisiblePreview} setIsModalVisible={setIsModalVisiblePreview}></PreviewSubject>
   {/* 查看引用 */}
   <QuoteSubject isModalVisible={isModalVisibleQuo}  setIsModalVisible={setIsModalVisibleQuo} quoteData={quoteData}></QuoteSubject>
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(SubjectLibrary)
